package com.liaoyin.travel.service.base;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.liaoyin.travel.vo.file.FileInfo;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.util.PartyUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FileService {

    @Value("${gate.file.uploadPath}")
    private String uploadPath;

    @Value("${gate.file.realPath}")
    private String realPath;

    @Value("${gate.file.server}")
    private String server;
    //
    // @Autowired
    // private HttpServletRequest request;

    public FileInfo savefile(MultipartFile file) {
        log.info("保存文件开始");
        /**
         * 首先将文件缓存到服务器上
         */
        // String root = request.getSession().getServletContext().getRealPath("");
        String fileName = createFileName(file.getOriginalFilename());
        // String savePath = root + "/" + uploadPath + fileName;
        String savePath = realPath + uploadPath + fileName;
        File saveFile = new File(savePath);
        if (saveFile.length() < 0) {
            return null;
        }
        try {
            file.transferTo(saveFile);
            // 设置访问权限，可读，所有人可读
            saveFile.setReadable(true, false);
        } catch (IllegalStateException | IOException e1) {
            log.info("文件保存时发生异常" + e1);
            throw new BusinessException("file.saveError", "文件保存出错");
        }
        log.info("保存文件结束");

        FileInfo fileInfo = new FileInfo();
        //原始文件名
        fileInfo.setFileName(file.getOriginalFilename());
        //保存路径，相对路径
        fileInfo.setFilePath(uploadPath + fileName);
        //文件类型
        fileInfo.setFileType(getFileSuffix(fileName));
        //文件大小
        fileInfo.setFileSize(PartyUtil.getFileSizeKb(saveFile.length()));
        //文件url
        fileInfo.setUrl(server + uploadPath + fileName);

        return fileInfo;
    }


    /**
     * @方法名：savefile
     * @描述： TODO
     * @作者： lijing
     * @日期： Created in 2018年9月20日
     */
    public FileInfo savefile(String base64File) {
        log.info("保存文件开始");
//        log.info(base64File);
        String suffix = "";
        if (base64File.startsWith("data:image/png")) {
            suffix = "png";
            base64File = base64File.replaceAll("data:image/png;base64,", "");
        } else if (base64File.startsWith("data:image/jpeg")) {
            suffix = "jpg";
            base64File = base64File.replaceAll("data:image/jpeg;base64,", "");
        } else if (base64File.startsWith("data:image/jepg")) {
//            log.info("test11111111111111111111111111");
            suffix = "jpg";
            base64File = base64File.replaceAll("data:image/jepg;base64,", "");
        } else if (base64File.startsWith("data:image/jpg")) {
            suffix = "jpg";
            base64File = base64File.replaceAll("data:image/jpg;base64,", "");
        }
        else if (base64File.startsWith("data:audio/mp3")) {
            suffix = "mp3";
            base64File = base64File.replaceAll("data:audio/mp3;base64,", "");
        }
        long fileSize = 0L;

        byte[] buffer = Base64.decodeBase64(base64File);
        // String root = request.getSession().getServletContext().getRealPath("");
        String fileName = createBase64FileName(suffix);
        String savePath = realPath + uploadPath + fileName;
        try {
            FileOutputStream out = new FileOutputStream(savePath);
            out.write(buffer);
            fileSize = out.getChannel().size();
            out.close();
        } catch (IllegalStateException | IOException e1) {
            log.info("文件保存时发生异常" + e1);
            throw new BusinessException("file.saveError", "文件保存出错");
        }
        log.info("文件路径:" + savePath);
        log.info("保存文件结束");

        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileName(fileName);
        fileInfo.setFilePath(uploadPath + fileName);
        fileInfo.setFileType(getFileSuffix(fileName));
        fileInfo.setFileSize(PartyUtil.getFileSizeKb(fileSize));
        fileInfo.setUrl(server + uploadPath + fileName);

        return fileInfo;
    }

//    public static void main(String[] args) throws Exception {
//        File file=new File("d:\\jpeg\\test.txt");
//        System.out.println(txt2String(file));
//        String str=txt2String(file).replaceAll("data:image/jepg;base64,", "");
//        byte[] buffer = Base64.decodeBase64(str);
//        FileOutputStream out = new FileOutputStream("d:\\jpeg\\test.jpg");
//        out.write(buffer);
////        fileSize = out.getChannel().size();
//        out.close();
//    }
//
//    public static String txt2String(File file){
//        StringBuilder result = new StringBuilder();
//        try{
//            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
//            String s = null;
//            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
//                result.append(System.lineSeparator()+s);
//            }
//            br.close();
//        }catch(Exception e){
//            e.printStackTrace();
//        }
//        return result.toString();
//    }

    // public void getFile(String id, OutputStream out, HttpServletResponse
    // response) throws UnsupportedEncodingException {
    // File file = new File("");
    // String fileName = file.getPath();
    // response.setHeader("Content-disposition",
    // String.format("attachment; filename=\"%s\"", new
    // String(fileName.getBytes("UTF-8"), "ISO-8859-1")));
    // long length = file.getLength();
    // response.setHeader("Content-Length", String.valueOf(length));
    // try {
    // file.writeTo(out);
    // } catch (IOException e) {
    // log.warn("下载停止");
    // }
    // }

    public boolean deleteFile(String id) {
        return true;
    }

    private String createFileName(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            throw new BusinessException("file.fileNameIsNull", "文件名为空");
        }
        String result = "";
        // 获取文件后缀
        String suffix = getFileSuffix(fileName);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String date = sdf.format(new Date());

        if (StringUtils.isNotBlank(suffix)) {
            result = date + "." + suffix;
        }
        return result;
    }

    private String createBase64FileName(String suffix) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String date = sdf.format(new Date());

        return date + "." + suffix;
    }

    private String getFileSuffix(String fileName) {
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (StringUtils.isNotBlank(suffix)) {
            suffix = suffix.toLowerCase();
        }
        return suffix;
    }

    public List<FileInfo> saveFileList(MultipartFile[] files){
        List<FileInfo> fileInfoList=new ArrayList<>();
        for(MultipartFile item : files) {
        	System.out.println( item.getName()+"//"+item.getSize());
            FileInfo fileInfo = this.savefile(item);
            fileInfoList.add(fileInfo);
        }
        return fileInfoList;
    }
}
